{% load static %}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>layout 管理界面大布局示例 - Layui</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="{% static '/layui/css/layui.css' %}">
  <style>
    table img {
        width: 90px;
    }
  </style>
</head>
<body>
<div class="layui-layout layui-layout-admin">
      {% include 'header.html' %}
  <div class="layui-body">
    <!-- 内容主体区域 -->
    <div style="padding: 15px;">
        <h2>修改用户</h2>
        <form class="layui-form" action="">
          <input type="hidden" name="id" value="{{ user.id }}">
          <div class="layui-form-item">
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-block">
              <input type="text" name="username" lay-verify="required" placeholder="请输入姓名" autocomplete="off" class="layui-input" value="{{ user.username }}">
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">年龄</label>
            <div class="layui-input-block">
              <input type="number" name="age" min="0" max="200" lay-affix="number" lay-verify="required" placeholder="请输入年龄" autocomplete="off" class="layui-input" value="{{ user.age }}">
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">分类</label>
            <div class="layui-input-block">
              <select name="category">
                <option value="-1">请选择</option>
                        <option value="1" {% if user.category == 1 %} selected {% endif %}>学生</option>
                        <option value="2" {% if user.category == 2 %} selected {% endif %}>老师</option>
                        <option value="3" {% if user.category == 3 %} selected {% endif %}>工人</option>
              </select>
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">头像</label>
            <div class="layui-input-block">
              <button type="button" class="layui-btn" id="ID-upload-demo-btn">
                <i class="layui-icon layui-icon-upload"></i> 图片上传
              </button>
              <div style="width: 132px;">
                <div class="layui-upload-list">
                  <img src="{% static 'imgs/' %}{{ user.icon }}" class="layui-upload-img" id="ID-upload-demo-img" style="width: 100%; height: 92px;">
                  <div id="ID-upload-demo-text"></div>
                </div>
                <div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="filter-demo">
                  <div class="layui-progress-bar" lay-percent=""></div>
                </div>
              </div>
            </div>
          </div>
          <div class="layui-form-item">
            <div class="layui-input-block">
              <button type="submit" class="layui-btn" lay-submit lay-filter="demo1">立即提交</button>
              <button type="reset" class="layui-btn layui-btn-primary">重置</button>
              <button class="layui-btn layui-btn-primary" onclick="history.back();return false;">返回</button>
            </div>
          </div>
        </form>
  </div>
  <div class="layui-footer">
    <!-- 底部固定区域 -->
    底部固定区域
  </div>
</div>
<script src="{% static 'layui/layui.js' %}"></script>
<script>
//1. 拿到id
const searchParams = new URLSearchParams(location.search);
var id = searchParams.get('id')
//2. 根据id从local storage取出对象 
var userlist = JSON.parse(localStorage.getItem('users'))
var user = userlist.find(item=>item.id==id)


//JS 
layui.use(['form','element', 'layer', 'util'], function(){
  var form = layui.form;
  var upload = layui.upload;
  var element = layui.element;
  var layer = layui.layer;
  var util = layui.util;
  var $ = layui.$;

  // 单图片上传
  var uploadInst = upload.render({
      elem: '#ID-upload-demo-btn',
      url: '/upload_img/', // 实际使用时改成您自己的上传接口即可。
      data: {csrfmiddlewaretoken: '{{ csrf_token }}'},
      field:'icon',
    before: function(obj){
      // 预读本地文件示例，不支持ie8
      obj.preview(function(index, file, result){
        $('#ID-upload-demo-img').attr('src', result); // 图片链接（base64）
      });

      element.progress('filter-demo', '0%'); // 进度条复位
      layer.msg('上传中', {icon: 16, time: 0});
    },
    done: function(res){
      // 若上传失败
      if(res.code > 0){
        localStorage.setItem('icon',res.data.file_name)
        return layer.msg('上传成功!');
      }
      // 上传成功的一些操作
      // …
      $('#ID-upload-demo-text').html(''); // 置空上传失败的状态
    },
    error: function(){
      // 演示失败状态，并实现重传
      var demoText = $('#ID-upload-demo-text');
      demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
      demoText.find('.demo-reload').on('click', function(){
        uploadInst.upload();
      });
    },
    // 进度条
    progress: function(n, elem, e){
      element.progress('filter-demo', n + '%'); // 可配合 layui 进度条元素使用
      if(n == 100){
        layer.msg('上传完毕', {icon: 1});
      }
    }
  });

  // 提交事件
  form.on('submit(demo1)', function(data) {
      var field = data.field; // 获取表单字段值
      // 显示填写结果，仅作演示用
      layer.alert(JSON.stringify(field), {
          title: '当前填写的字段值'
      });
      // 此处可执行 Ajax 等操作
      // 新的用户数据存入localStorage
      // 1. 组装一个完整的用户对象。
      var user = {
          id: field.id,
          username: field.username,
          age: field.age,
          category: field.category,
          icon: localStorage.getItem("icon"),
          csrfmiddlewaretoken: '{{ csrf_token }}',
      }
    $.ajax({
          url: '/user/edit/',
          method: "POST",
          data: user,
          success: function (res) {
              console.log(res);
              layer.msg(res.msg)
          },
          error: function (err) {
              console.log(err);
          }
      })
      return false;
  });
    //2. 存入localStorage
    // 2.1 取出，转换成obj
    // 2.2 用户添加进去userlist -- 覆盖原来的
    {#var idx = userlist.findIndex(item=>item.id==id)#}
    {#userlist[idx] = user#}
    {##}
    {#// 2.3 新的userlist再次存入localStorage#}
    {#localStorage.setItem('users', JSON.stringify(userlist))#}
    {#return false; // 阻止默认 form 跳转#}


  
  //头部事件
  util.event('lay-header-event', {
    menuLeft: function(othis){ // 左侧菜单事件
      layer.msg('展开左侧菜单的操作', {icon: 0});
    },
    menuRight: function(){  // 右侧菜单事件
      layer.open({
        type: 1,
        title: '更多',
        content: '<div style="padding: 15px;">处理右侧面板的操作</div>',
        area: ['260px', '100%'],
        offset: 'rt', // 右上角
        anim: 'slideLeft', // 从右侧抽屉滑出
        shadeClose: true,
        scrollbar: false
      });
    }
  });
});
</script>
</div>
</body>
</html>